<template>
  <div>
    <Divider plain orientation="left">基础要素</Divider>
    <!-- <span @click="() => HANDLEMAP.insertSvg()" :draggable="true" @dragend="HANDLEMAP.insertSvg()">
        SVG文件
      </span>
      <span
        @click="() => HANDLEMAP.insertSvgStrModal()"
        :draggable="true"
        @dragend="HANDLEMAP.insertSvgStrModal()"
      >
        SVG字符
      </span> -->
    <div class="tool-boxs">
      <div
        class="box"
        @click="() => addTextBox1()"
        :draggable="true"
        @dragend="onDragend('textBox1')"
      >
        <Icon icon="bi:type-h1" width="40" />
        <span>大标题</span>
      </div>
      <div
        class="box"
        @click="() => addTextBox()"
        :draggable="true"
        @dragend="onDragend('textBox')"
      >
        <Icon icon="bi:type-h2" width="40" />
        <span>大标题</span>
      </div>
      <div
        class="box"
        @click="() => insertImgFile(img)"
        :draggable="true"
        @dragend="insertImgFile(img)"
      >
        <Icon icon="radix-icons:image" width="40" />
        <span>图片</span>
      </div>
      <div class="box" @click="() => addCircle()" :draggable="true" @dragend="onDragend('circle')">
        <Icon icon="ic:baseline-circle" width="40" />
        <span>圆形</span>
      </div>
      <div class="box" @click="() => addRect()" :draggable="true" @dragend="onDragend('rect')">
        <Icon icon="ion:square-sharp" width="40" />
        <span>正方形</span>
      </div>
      <div
        class="box"
        @click="() => addTriangle()"
        :draggable="true"
        @dragend="onDragend('triangle')"
      >
        <Icon icon="teenyicons:triangle-solid" width="40" />
        <span>三角形</span>
      </div>
      <div
        class="box"
        @click="() => addPolygon()"
        :draggable="true"
        @dragend="onDragend('polygon')"
      >
        <Icon icon="teenyicons:triangle-solid" width="40" />
        <span>多边形</span>
      </div>
    </div>
    <Divider plain orientation="left">画笔</Divider>

    <div
      class="boxs"
      :style="{ backgroundColor: penData.open ? '#cccccc7a' : '' }"
      @click="() => (canvasEditor.canvas.isDrawingMode = penData.open = !penData.open)"
    >
      <Icon icon="ph:pen-duotone" width="40" />
      <span>自定义画笔</span>
    </div>
    <Row justify="space-around">
      <Col>
        颜色
        <ColorPicker
          v-model="penData.color"
          @on-change="() => (canvasEditor.canvas.freeDrawingBrush.color = penData.color)"
        />
      </Col>
      <Col>
        粗细
        <InputNumber
          :min="1"
          v-model="penData.width"
          @on-change="() => (canvasEditor.canvas.freeDrawingBrush.width = penData.width)"
        />
      </Col>
    </Row>
    <div style="display: inline-block">
      <Modal
        v-model="state.showModal"
        title="请输入"
        @on-ok="insertTypeHand('insertSvgStr')"
        @on-cancel="showModal = false"
      >
        <Input
          v-model="state.svgStr"
          show-word-limit
          type="textarea"
          placeholder="请输入SVG字符串"
        />
      </Modal>
    </div>
    <!-- <Divider plain orientation="left">绘制元素</Divider>
    <div class="tool-box">
      <span
        @click="drawingLineModeSwitch(false)"
        :class="state.isDrawingLineMode && !state.isArrow && 'bg'"
      >
        <svg
          t="1673022047861"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="4206"
          width="20"
          height="20"
        >
          <path
            d="M187.733333 1024h-170.666666c-10.24 0-17.066667-6.826667-17.066667-17.066667v-170.666666c0-10.24 6.826667-17.066667 17.066667-17.066667h170.666666c10.24 0 17.066667 6.826667 17.066667 17.066667v170.666666c0 10.24-6.826667 17.066667-17.066667 17.066667zM34.133333 989.866667h136.533334v-136.533334H34.133333v136.533334zM1006.933333 204.8h-170.666666c-10.24 0-17.066667-6.826667-17.066667-17.066667v-170.666666c0-10.24 6.826667-17.066667 17.066667-17.066667h170.666666c10.24 0 17.066667 6.826667 17.066667 17.066667v170.666666c0 10.24-6.826667 17.066667-17.066667 17.066667zM853.333333 170.666667h136.533334V34.133333h-136.533334v136.533334z"
            fill=""
            p-id="4207"
          ></path>
          <path
            d="M187.733333 853.333333c-3.413333 0-10.24 0-13.653333-3.413333-6.826667-6.826667-6.826667-17.066667 0-23.893333l648.533333-648.533334c6.826667-6.826667 17.066667-6.826667 23.893334 0s6.826667 17.066667 0 23.893334l-648.533334 648.533333c0 3.413333-6.826667 3.413333-10.24 3.413333z"
            fill=""
            p-id="4208"
          ></path>
        </svg>
      </span>
      <span
        @click="drawingLineModeSwitch(true)"
        :class="state.isDrawingLineMode && state.isArrow && 'bg'"
      >
        <svg
          t="1673026778912"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="2659"
          width="20"
          height="20"
        >
          <path
            d="M320 738.133333L827.733333 230.4l-29.866666-29.866667L290.133333 708.266667v-268.8h-42.666666v341.333333h341.333333v-42.666667H320z"
            fill="#444444"
            p-id="2660"
          ></path>
        </svg>
      </span>
    </div> -->
  </div>
</template>

<script setup name="Tools">
// import { getImgStr, selectFiles } from '@/utils/utils';
import { Icon } from '@iconify/vue';
import useSelect from '@/hooks/select';
import { v4 as uuid } from 'uuid';
// import initializeLineDrawing from '@/core/remove/initializeLineDrawing';
import { getPolygonVertices } from '@/utils/math';
import img from '@/assets/logo.webp';
const { fabric, canvasEditor } = useSelect();

const penData = reactive({
  open: canvasEditor.canvas.isDrawingMode,
  color: canvasEditor.canvas.freeDrawingBrush.color,
  width: canvasEditor.canvas.freeDrawingBrush.width,
});
// const HANDLEMAP = {
//   // 插入图片
//   insertImg: function () {
//     selectFiles({ accept: 'image/*', multiple: true }).then((fileList) => {
//       Array.from(fileList).forEach((item) => {
//         getImgStr(item).then((file) => {
//           insertImgFile(file);
//         });
//       });
//     });
//   },
//   // 插入Svg
//   insertSvg: function () {
//     selectFiles({ accept: '.svg', multiple: true }).then((fileList) => {
//       Array.from(fileList).forEach((item) => {
//         getImgStr(item).then((file) => {
//           insertSvgFile(file);
//         });
//       });
//     });
//   },
//   // 插入SVG元素
//   insertSvgStrModal: function () {
//     state.svgStr = '';
//     state.showModal = true;
//   },
//   // 插入字符串元素
//   insertSvgStr: function () {
//     fabric.loadSVGFromString(state.svgStr, (objects, options) => {
//       const item = fabric.util.groupSVGElements(objects, {
//         ...options,
//         name: 'defaultSVG',
//         id: uuid(),
//       });
//       canvasEditor.canvas.add(item).centerObject(item).renderAll();
//     });
//   },
// };

// 插入图片文件
function insertImgFile(file) {
  if (!file) throw new Error('file is undefined');
  const imgEl = document.createElement('img');
  imgEl.src = file;
  // 插入页面
  document.body.appendChild(imgEl);
  imgEl.onload = () => {
    // 创建图片对象
    const imgInstance = new fabric.Image(
      imgEl,
      {
        id: uuid(),
        name: 'image',
        left: 100,
        top: 100,
        imgUrl: file,
      },
      { crossOrigin: 'anonymous' }
    );
    // 设置缩放
    canvasEditor.canvas.add(imgInstance);
    canvasEditor.canvas.setActiveObject(imgInstance);
    canvasEditor.canvas.renderAll();
    // 删除页面中的图片元素
    imgEl.remove();
  };
}

// // 插入文件元素
// function insertSvgFile(svgFile) {
//   if (!svgFile) throw new Error('file is undefined');
//   fabric.loadSVGFromURL(svgFile, (objects, options) => {
//     const item = fabric.util.groupSVGElements(objects, {
//       ...options,
//       name: 'defaultSVG',
//       id: uuid(),
//     });
//     canvasEditor.canvas.add(item).centerObject(item).renderAll();
//   });
// }

// 默认属性
const defaultPosition = { shadow: '', fontFamily: 'arial' };
// 拖拽属性
const dragOption = {
  left: 0,
  top: 0,
};
const state = reactive({
  isDrawingLineMode: false,
  isArrow: false,
  showModal: false,
  svgStr: '',
});
// let drawHandler = null;

const addText = (option) => {
  const text = new fabric.IText('单行文本', {
    ...defaultPosition,
    ...option,
    fontSize: 80,
    id: uuid(),
  });
  canvasEditor.canvas.add(text);
  if (!option) {
    text.center();
  }
  canvasEditor.canvas.setActiveObject(text);
};

const addTextBox = (option) => {
  const text = new fabric.Textbox('我是一只小小小小鸟，', {
    ...defaultPosition,
    ...option,
    splitByGrapheme: true,
    width: 800,
    fontSize: 80,
    id: uuid(),
  });
  canvasEditor.canvas.add(text);
  if (!option) {
    text.center();
  }
  canvasEditor.canvas.setActiveObject(text);
};

const addTextBox1 = (option) => {
  const text = new fabric.Textbox('想要飞得更高！', {
    ...defaultPosition,
    ...option,
    splitByGrapheme: true,
    width: 600,
    fontSize: 100,
    id: uuid(),
  });
  canvasEditor.canvas.add(text);
  if (!option) {
    text.center();
  }
  canvasEditor.canvas.setActiveObject(text);
};

const addTriangle = (option) => {
  const triangle = new fabric.Triangle({
    ...defaultPosition,
    ...option,
    width: 400,
    height: 400,
    fill: '#92706B',
    id: uuid(),
    name: '三角形',
  });
  canvasEditor.canvas.add(triangle);
  if (!option) {
    triangle.center();
  }
  canvasEditor.canvas.setActiveObject(triangle);
};

const addPolygon = (option) => {
  const polygon = new fabric.Polygon(getPolygonVertices(5, 200), {
    ...defaultPosition,
    ...option,
    fill: '#ccc',
    id: uuid(),
    name: '多边形',
  });
  polygon.set({
    // 创建完设置宽高，不然宽高会变成自动的值
    width: 400,
    height: 400,
    // 关闭偏移
    pathOffset: {
      x: 0,
      y: 0,
    },
  });
  canvasEditor.canvas.add(polygon);
  if (!option) {
    polygon.center();
  }
  canvasEditor.canvas.setActiveObject(polygon);
};

const addCircle = (option) => {
  const circle = new fabric.Circle({
    ...defaultPosition,
    ...option,
    radius: 150,
    fill: '#57606B',
    id: uuid(),
    name: '圆形',
  });
  canvasEditor.canvas.add(circle);
  if (!option) {
    circle.center();
  }
  canvasEditor.canvas.setActiveObject(circle);
};

const addRect = (option) => {
  const rect = new fabric.Rect({
    ...defaultPosition,
    ...option,
    fill: '#F57274',
    width: 400,
    height: 400,
    id: uuid(),
    name: '矩形',
  });
  canvasEditor.canvas.add(rect);
  if (!option) {
    rect.center();
  }
  canvasEditor.canvas.setActiveObject(rect);
};
// const drawingLineModeSwitch = (isArrow) => {
//   state.isArrow = isArrow;
//   state.isDrawingLineMode = !state.isDrawingLineMode;
//   canvasEditor.setMode(state.isDrawingLineMode);
//   canvasEditor.setArrow(isArrow);
//   canvasEditor.canvas.forEachObject((obj) => {
//     if (obj.id !== 'workspace') {
//       obj.selectable = !state.isDrawingLineMode;
//       obj.evented = !state.isDrawingLineMode;
//     }
//   });
// };

// 拖拽开始时就记录当前打算创建的元素类型
const onDragend = (type) => {
  // todo 拖拽优化 this.canvas.editor.dragAddItem(event, item);
  switch (type) {
    case 'text':
      addText(dragOption);
      break;
    case 'textBox':
      addTextBox(dragOption);
      break;
    case 'textBox1':
      addTextBox1(dragOption);
      break;
    case 'rect':
      addRect(dragOption);
      break;
    case 'circle':
      addCircle(dragOption);
      break;
    case 'triangle':
      addTriangle(dragOption);
      break;
    case 'polygon':
      addPolygon(dragOption);
      break;
    default:
  }
};

onMounted(() => {
  nextTick(() => {
    // 线条绘制
    // drawHandler = initializeLineDrawing(canvasEditor.canvas, defaultPosition);

    canvasEditor.canvas.on('drop', (opt) => {
      // 画布元素距离浏览器左侧和顶部的距离
      const offset = {
        left: canvasEditor.canvas.getSelectionElement().getBoundingClientRect().left,
        top: canvasEditor.canvas.getSelectionElement().getBoundingClientRect().top,
      };

      // 鼠标坐标转换成画布的坐标（未经过缩放和平移的坐标）
      const point = {
        x: opt.e.x - offset.left,
        y: opt.e.y - offset.top,
      };

      // 转换后的坐标，restorePointerVpt 不受视窗变换的影响
      const pointerVpt = canvasEditor.canvas.restorePointerVpt(point);
      dragOption.left = pointerVpt.x;
      dragOption.top = pointerVpt.y;
    });
  });
});
</script>

<style scoped lang="less">
.boxs {
  display: flex;
  justify-content: space-evenly;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
  height: 80px;
  font-size: 12px;
  border-radius: 15px;
  border: 1px dashed #cccccc7a;
}

.tool-boxs {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  .box {
    display: flex;
    justify-content: space-evenly;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
    width: 70px;
    height: 85px;
    font-size: 12px;
    border-radius: 15px;
  }
  .boxs {
    text-align: center;
    width: 100%;
  }
  .box:hover {
    background-color: #cccccc7a;
  }
}
</style>
